<?php
/**
 * Created by PhpStorm.
 * User: dancheng
 * Date: 2018/1/26
 * Time: 8:50
 */
class Usertoken_helper{
    public $CI;
    public function __construct(){
        $this->CI = &get_instance();//获取CI对象
        $this->CI->load->model('user_token_model');
    }

    /**
     * @param $th
     * @return array
     * 登录过滤.
     */
    public function check_userToken($th){
        if(isset($_POST['user_token'])){
            $user_token = $_POST['user_token'];
        } else if(isset($_GET['user_token'])){
            $user_token = $_GET['user_token'];
        } else {
            $user_token = '0';
        }

        $data_user_token = [];
        if(!$user_token == '0'&&!$user_token==""){

            $user_token = json_decode($user_token, true);
            $user = $this->CI->user_token_model->findById($user_token['user_id']);
            if(strtotime($user['expire_time'])>strtotime(date('Y-m-d H:i:s'))){//如果没过期
                $data=array(
                    'user_id'=>$user['user_id'],
                    'update_time'=>date("Y-m-d H:i:s"),
                    'expire_time'=>date("Y-m-d H:i:s",strtotime("+1 weeks")),
                );
                $this->CI->user_token_model->update($data);
                $data_user_token['msg'] = '用户已登录';
                $data_user_token['flag'] = 1;
            }else{
                $data_user_token['msg'] = '用户登录已过期';
                $data_user_token['flag'] = 0;
            }
        } else {
            $data_user_token['msg'] = '没有用户登录';
            $data_user_token['flag'] = 0;
        }
        return $data_user_token;
    }

    /**
     * @param $th
     * @return array
     * token令牌验证
     */
    public function check_token($th){
        if($th->input->is_ajax_request()){
            if(isset($_POST['token'])){
                $token = $_POST['token'];
            } else if(isset($_GET['token'])){
                $token = $_GET['token'];
            } else {
                $token = '0';
            }
            if($token === token_key){
                $token_data = [
                    'tag' => 1,
                    'msg' => 'token合法，可以访问',
                ];
            } else {
                $token_data = [
                    'tag' => 0,
                    'msg' => 'token不合法，不可以访问',
                ];
            }
            return $token_data;
        }
    }
}